<?php

namespace app\home\controller;

use think\Controller;
use QL\QueryList;
use app\Model\model\GoodsImage;
use app\Model\model\GoodsSku;
use app\Model\model\Goods;
use app\Model\model\UploadFile;
use QL\Ext\PhantomJs;

/**
 * 工具类
 * Class Tool
 * @package app\home\controller
 */
class Tool extends Controller
{


    /**
     * 请求数据方法
     * @param $url
     * @param int $ifpost
     * @param string $datafields
     * @param string $cookiefile
     * @param bool $v
     * @return bool|string
     */
    protected function curl($url, $ifpost = 0, $datafields = '', $cookiefile = '', $v = false)
    {
        // 伪造IP
        $xforip = rand(1, 254) . "." . rand(1, 254) . "." . rand(1, 254) . "." . rand(1, 254);
        $header = array("Connection: Keep-Alive", "Accept: application/json, text/javascript, */*; q=0.01", "Pragma: no-cache", "Accept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3", "User-Agent: Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14", 'CLIENT-IP:' . $xforip, 'X-FORWARDED-FOR:' . $xforip); // 请求头信息
        $ch = curl_init();
        // 使用伪造代理IP
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, $v);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $ifpost && curl_setopt($ch, CURLOPT_POST, $ifpost);
        $ifpost && curl_setopt($ch, CURLOPT_POSTFIELDS, $datafields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
        $cookiefile && curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
        $cookiefile && curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }

    /**
     * 中韩翻译接口
     * @param string $str 要翻译的中文内容
     * @return array 包括 type:ZH_CN2KR src:透明 tgt:투명
     */
    protected function translation($str)
    {
        $api = "http://fanyi.youdao.com/translate?&doctype=json&type=ZH_CN2KR&i="; // 日韩翻译接口
        $res = $this->curl($api . $str, 1);
        $res = $this->jsonArray($res);
        return array('type' => $res['type'], 'src' => $res['translateResult'][0][0]['src'], 'tgt' => $res['translateResult'][0][0]['tgt']);
    }

    /**
     *   远程下载本地图片
     * @param string 下载图片路径
     * @param string 指定文件名
     * @param string 保存路径
     * @return array 文件信息（【路径+文件名-returnFile】 【文件名-FileName】 【后缀名（如.jpeg）-extension】 【路径-path】）
     */
    protected function downloadImageFromUrl($url, $goods_id, $fileName = '', $path = "./upload/img/")
    {
        // 建立一个临时文件，用于保存
        $tmpFile = tempnam(sys_get_temp_dir(), 'image');
        # 文件下载 BEGIN #
        // 打开临时文件，用于写入（w),b二进制文件
        $resource = fopen($tmpFile, 'wb');
        // 初始化curl
        $curl = curl_init($url);
        // 设置输出文件为刚打开的
        curl_setopt($curl, CURLOPT_FILE, $resource);
        // 不需要头文件
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_TIMEOUT, 20);
        // 执行
        curl_exec($curl);
        // 关闭curl
        curl_close($curl);
        // 关闭文件
        fclose($resource);
        # 文件下载 END #
        // 获取文件类型
        if (function_exists('exif_imagetype')) {
            // 读取一个图像的第一个字节并检查其签名(这里需要打开mbstring及php_exif)
            $fileType = exif_imagetype($tmpFile);
        } else {
            // 获取文件大小，里面第二个参数是文件类型 （这里后缀可以直接通过getimagesize($url)来获取，但是很慢）
            @$fileInfo = getimagesize($tmpFile);
            if (!$fileInfo) {
                // 获取图像信息失败,再次调用一次
                $this->log("获取图像信息失败的图片地址：" . $url . " 商品ID：" . $goods_id, './upload/error.txt');
                echo "<br><b><font color='red'>有一条图像信息本地化失败，已记录！</font></b><br/>";
                $returnFile = $path . $fileName . 'xxxx' . '.jpeg';
                return array('returnFile' => $returnFile, 'FileName' => $fileName, 'extension' => 'jpeg', 'path' => $path);

            }
            $fileType = $fileInfo[2];
        }
        // 根据文件类型获取后缀名
        $extension = image_type_to_extension($fileType);

        // 如果未指定文件名则使用MD5散列值
        if ($fileName == '') {
            // 计算指定文件的 MD5 散列值，作为保存的文件名，重复下载同一个文件不会产生重复保存，相同的文件散列值相同
            $md5FileName = md5_file($tmpFile);
        } else {
            $md5FileName = $fileName;
        }

        // 最终保存的文件
        $returnFile = $path . $md5FileName . $extension;
        // 检查传过来的路径是否存在，不存在就创建
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        // 复制临时文件到最终保存的文件中
        copy($tmpFile, $returnFile);
        // 释放临时文件
        @unlink($tmpFile);
        // 返回文件信息
        return array(
            'returnFile' => $returnFile,
            'FileName' => $md5FileName,
            'extension' => trim($extension, '.'),
            'path' => $path
        );
    }


    // 记录日志
    protected function log($msg, $path = './upload/img.txt')
    {
        file_put_contents($path, $msg . "\r\n", FILE_APPEND);
    }

    /**
     * 删除指定商品相关表内容
     * @param $goods_id
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    protected function delGoods($goods_id)
    {
        GoodsSku::where('goods_id', $goods_id)->delete();
        Goods::where('goods_id', $goods_id)->delete();
        GoodsImage::where('goods_id', $goods_id)->delete();
        return 200;
    }

    /**
     * 图片信息到数据库
     * @param $file_name 文件名+后缀名
     * @param $extension 后缀名
     * @return int|mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function saveImg($file_name, $extension)
    {
        if ($data = UploadFile::where('file_name', $file_name)->find()) {
            // 有相同数据则直接返回文件 id
            return $data['file_id'];
        }
        return UploadFile::insertGetId([
            'storage' => 'local',
            'group_id' => 0,
            'file_name' => $file_name,
            'file_size' => 2000,
            'extension' => $extension,
            'wxapp_id' => 10001,
            'file_type' => 'image',
            'create_time' => time()
        ]);
    }

    /**
     * 图片信息存储到商品图片表
     * @param $goods_id
     * @param $image_id
     * @return bool|int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function saveGoodsImg($goods_id, $image_id)
    {
        if (GoodsImage::where(['goods_id' => $goods_id, 'image_id' => $image_id])->find()) {
            return true;
        }
        return GoodsImage::insert(['goods_id' => $goods_id, 'image_id' => $image_id, 'create_time' => time()]);
    }


    /**
     * json转数组
     * @param $json
     * @return mixed
     */
    protected function jsonArray($json)
    {
        return json_decode($json, true);
    }

    /**
     * 取文本中间
     * @param $str
     * @param $leftStr
     * @param $rightStr
     * @return false|string
     */
    protected function getIntermediate($str, $leftStr, $rightStr)
    {
        $left = strpos($str, $leftStr);
        $right = strpos($str, $rightStr, $left);
        if ($left < 0 or $right < $left) return '';
        return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
    }

    /**取文本右边
     * @param $str
     * @param $leftStr
     * @return false|string
     */
    protected function getRight($str, $leftStr)
    {
        $left = strpos($str, $leftStr);
        return substr($str, $left + strlen($leftStr));
    }

    /**
     * 取文本左边
     * @param $str
     * @param $rightStr
     * @return false|string
     */
    protected function getLeft($str, $rightStr)
    {
        $right = strpos($str, $rightStr);
        return substr($str, 0, $right);
    }


    /**
     * 动态获取 js 渲染页面插件
     * @param $url
     * @return mixed
     */
    protected function usePhantomJs($url)
    {
        $ql = QueryList::getInstance();
        $ql->use(PhantomJs::class, '/www/wwwroot/frp.wslmf.com/tp5/public/phantomjs/bin/phantomjs');
        $ql->use(PhantomJs::class, '/www/wwwroot/frp.wslmf.com/tp5/public/phantomjs/bin/phantomjs', 'browser');
        $html = $ql->browser($url)->getHtml();
        $ql->destruct(); // 释放内存
        return $html;
    }

    /**
     * 获取指定模板采集规则
     * @param $type
     */
    protected function rules($type)
    {
        switch ($type) {
            case 'info1':
                $rules = [
                    'goods_sku' => ['.pd-no', 'text', '', function ($content) {
                        $content = $this->getRight($content, 'SKU.NO');
                        return trim($content, ' ');
                    }],
                    'content' => ['#classification_table', 'html'],
                    'area' => ['#classification_table .last td', 'text'],
                    'skuinfo' => ['#classification_table tr:first-child td', 'text']
                ];
                return $rules;
                break;
            case 'img1':
                $rules = ['img' => ['.pr_wrap .pd-thumb-list a img', 'data-image']];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info2':
                $rules = [
                    'goods_sku' => ['.list_info:eq(0) .txt:eq(1)', 'text'],
                    'content' => ['.prd_tab_view:eq(2)', 'html'],
                    'area' => ['.prd_tab_view:eq(2) dl dd:eq(8)', 'text'],
                    'skuinfo' => ['.prd_tab_view:eq(2) dl dd:eq(0)', 'text']
                ];
                return $rules;
                break;
            case 'img2':
                $rules = [
                    'img' => ['.swiper-wrapper:eq(0) .swiper-slide img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info3':
                $rules = [
                    'goods_sku' => ['.prd_price:eq(1) dl:nth-child(2) dd', 'text'],
                    'content' => ['.description_info:eq(3)', 'html'],
                    'area' => ['.description_info:eq(3) dl:nth-child(11) dd', 'text'],
                    'skuinfo' => ['.description_info:eq(3) dl:nth-child(1) dd', 'text'],
                ];
                return $rules;
                break;
            case 'img3':
                $rules = [
                    'img' => ['.swiper-wrapper:eq(0) .swiper-slide img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info4':
                $rules = [
                    'goods_sku' => ['tbody:eq(0) tr:nth-child(2) td', 'text'],
                    'content' => ['#tabsdiv-2', 'html'],
                    'area' => ['#tabsdiv-2 tbody tr:nth-child(8) td', 'text'],
                    'skuinfo' => ['#tabsdiv-2 tbody tr:nth-child(1) td', 'text'],
                ];
                return $rules;
                break;
            case 'img4':
                $rules = [
                    'img' => ['.leftSection .pimg img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info5':
                $rules = [
                    'goods_sku' => ['.prodSpec tr:nth-child(2) td', 'text'],
                    'content' => ['.tableStyle2', 'html'],
                    'skuinfo' => ['.tableStyle2 tr:nth-child(1) td', 'text']
                ];
                return $rules;
                break;
            case 'img5':
                $rules = [
                    'img' => ['.prodImg img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info6':
                $rules = [
                    'goods_sku' => ['.infoTable tbody tr:nth-child(2) td', 'text'],
                    'content' => ['#Detail-info', 'html'],
                    'area' => ['#Detail-info tr:nth-child(10) td', 'text'],
                    'skuinfo' => ['#Detail-info tr:nth-child(1) td', 'text'],
                ];
                return $rules;
                break;
            case 'img6':
                $rules = [
                    'img' => ['#prodImg', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info7':
                $rules = [
                    'goods_sku' => ['.pro-buy-info dl:nth-child(2) dd', 'text'],
                    'content' => ['#info3', 'html'],
                    'area' => ['#info3 dl:nth-child(10) dd', 'text'],
                    'skuinfo' => ['#info3 dl:nth-child(1) dd', 'text'],
                ];
                return $rules;
                break;
            case 'img7':
                $rules = [
                    'img' => ['.pro-img-list img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info8':
                $rules = [
                    'goods_sku' => ['.detail-text-box:eq(0) dl:nth-child(2) dd', 'text'],
                    'content' => ['.detail-text-box:eq(1)', 'html'],
                    'area' => ['.detail-text-box:eq(1) ul:eq(8)', 'text'],
                    'skuinfo' => ['.detail-text-box:eq(1) ul:eq(0)', 'text'],
                ];
                return $rules;
                break;
            case 'img8':
                $rules = [
                    'img' => ['.img-item img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info9':
                $rules = [
                    'goods_sku' => ['.buy_box .bu_list:nth-child(2)', 'text', '', function ($content) {
                        $content = trim($content, ' ');
                        return $content;
                    }],
                    'content' => ['#tabMenu0', 'html'],
                    'area' => ['#tabMenu0 tr:nth-child(6) td', 'text'],
                    'skuinfo' => ['#tabMenu0 tr:nth-child(1) td', 'text'],
                ];
                return $rules;
                break;
            case 'img9':
                $rules = [
                    'img' => ['.productimg img:eq(0)', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info10':
                $rules = [
                    'goods_sku' => ['.inner tbody tr:nth-child(2) td', 'text'],
                    'content' => ['.dataTable tbody', 'html', '', function ($content) {
                        $content = "<table><tbody>{$content}</tbody></table>";
                        return $content;
                    }],
                    'area' => ['.dataTable tr:nth-child(10) td', 'text'],
                    'skuinfo' => ['.dataTable tr:nth-child(1) td', 'text'],
                ];
                return $rules;
                break;
            case 'img10':
                $rules = [
                    'img' => ['.prodImage img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info11':
                $rules = [
                    'goods_sku' => ['.sabon:eq(2)', 'text', '', function ($content) {
                        $content = $this->getRight($content, 'SKU.NO');
                        return trim($content, ' ');
                    }],
                    'content' => ['.tbl-2', 'html', '', function ($content) {
                        $content = '<table><tbody>' . $content . '</tbody></table>';
                        return $content;
                    }],
                    'area' => ['.tbl-2 .last td', 'text'],
                    'skuinfo' => ['.tbl-2 tbody tr:nth-child(1) td', 'text'],
                ];
                return $rules;
                break;
            case 'img11':
                $rules = [
                    'img' => ['.primary-image', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info12':
                $rules = [
                    'goods_sku' => ['.prod_buyinfo:eq(0) tbody tr:nth-child(2) td', 'text'],
                    'content' => ['.prod_buyinfo:eq(1)', 'html'],
                    'area' => ['.prod_buyinfo:eq(1) tr:nth-child(6) td', 'text'],
                    'skuinfo' => ['.prod_buyinfo:eq(1) tr:nth-child(1) td', 'text'],
                ];
                return $rules;
                break;
            case 'img12':
                $rules = [
                    'img' => ['#pd-img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info13':
                $rules = [
                    'goods_sku' => ['.prodInfoTbl tr:nth-child(2) td', 'text'],
                    'content' => ['.dataTable', 'html', '', function ($content) {
                        $content = '<table>' . $content . '</table>';
                        return $content;
                    }],
                    'area' => ['.dataTable tr:nth-child(10) td', 'text'],
                    'skuinfo' => ['.dataTable tr:nth-child(1) td', 'text'],
                ];
                return $rules;
                break;
            case 'img13':
                $rules = [
                    'img' => ['.bimg img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info14':
                $rules = [
                    'goods_sku' => ['.prd_info:eq(0) ul', 'text', '', function ($content) {
                        $content = $this->getRight($content, 'SKU.NO');
                        return $content;
                    }],
                    'content' => ['.description_info:eq(2)', 'html'],
                    'area' => ['.description_info:eq(2) dl:nth-child(11) dd', 'text'],
                    'skuinfo' => ['.description_info:eq(2) dl:nth-child(1) dd', 'text'],
                ];
                return $rules;
                break;
            case 'img14':
                $rules = [
                    'img' => ['.swiper-wrapper:eq(0) img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info15':
                $rules = [
                    'goods_sku' => ['.prod_buyinfo:eq(0) tbody tr:nth-child(2) td', 'text'],
                    'content' => ['.product-view-table', 'html'],
                    'area' => ['.product-view-table tr:nth-child(10) td', 'text'],
                    'skuinfo' => ['.product-view-table tr:nth-child(1) td', 'text'],
                ];
                return $rules;
                break;
            case 'img15':
                $rules = [
                    'img' => ['#clinique_zoom img', 'src']
                ];
                return $rules;
                break;
            //---------------------------------------------------------------------------
            case 'info16':
                $rules = [
                    'goods_sku' => ['.prd_info:eq(0) dd ul li:nth-child(2)', 'text', '', function ($content) {
                        $content = $this->getRight($content, 'SKU.NO');
                        return trim($content, ' :');
                    }],
                    'content' => ['.description_info:eq(2)', 'html'],
                    'area' => ['.description_info:eq(2) dl:nth-child(10) dd', 'text'],
                    'skuinfo' => ['.description_info:eq(2) dl:nth-child(1) dd', 'text'],
                ];
                return $rules;
                break;
            case 'img16':
                $rules = [
                    'img' => ['.swiper-wrapper:eq(0) img', 'src']
                ];
                return $rules;
                break;
            //---------------------------------------------------------------------------
            case 'info17':
                $rules = [
                    'goods_sku' => ['.list_info:eq(0) li:nth-child(2) .txt', 'text'],
                    'content' => ['.prd_tab_view:eq(2)', 'html'],
                    'area' => ['.prd_tab_view:eq(2) dl dd:eq(8)', 'text'],
                    'skuinfo' => ['.prd_tab_view:eq(2) dl dd:eq(0)', 'text']
                ];
                return $rules;
                break;
            case 'img17':
                $rules = [
                    'img' => ['.zoom img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info18':
                $rules = [
                    'goods_sku' => ['.list_info:eq(0) .txt:eq(1)', 'text'],
                    'content' => ['.prd_tab_view:eq(3)', 'html'],
                    'area' => ['.prd_tab_view:eq(3) dl dd:eq(8)', 'text'],
                    'skuinfo' => ['.prd_tab_view:eq(3) dl dd:eq(0)', 'text']
                ];
                return $rules;
                break;
            case 'img18':
                $rules = [
                    'img' => ['.swiper-wrapper:eq(0) .swiper-slide img', 'src']
                ];
                return $rules;
                break;

            //---------------------------------------------------------------------------
            case 'info19':
                $rules = [
                    'goods_sku' => ['.prod_info dl:nth-child(2) dd', 'text'],
                    'content' => ['#prodtabs2-1', 'html'],
                    'area' => ['#prodtabs2-1 dl dd:eq(8)', 'text'],
                    'skuinfo' => ['#prodtabs2-1 tr:nth-child(1) td', 'text']
                ];
                return $rules;
                break;
            case 'img19':
                $rules = [
                    'img' => ['.stage-item img', 'src']
                ];
                return $rules;
                break;

        }
    }


}
